var shortName = 'icontrol'; 
var version = '1.0'; 
var displayName = 'PhoneGap Test Database'; 
var maxSize = 1000000; // in bytes 
var mydb = openDatabase(shortName, version, displayName, maxSize);  
var dataString="";
var fileData="";

var url="https://intensecontrol.com/pensonic/main/tablet_upload_act.jsp"; //put in the ip address of the server to ping here

var sourcePaths=new Array();
var fileList=new Array();


var connectionAvailable=false;
var pingURL="https://intensecontrol.com/pensonic/main/tablet_upload_act.jsp"; //put in the ip address of the server to ping here

 function initDB() 
{

    try { 
        if (!window.openDatabase) { 
            alert('not supported'); 
        } else { 
            var shortName = 'dps2'; 
            var version = '1.0'; 
            var displayName = 'PhoneGap Test Database'; 
            var maxSize = 1000000; // in bytes y
            var mydb = openDatabase(shortName, version, displayName, maxSize); 
        }
    } catch(e) { 
        // Error handling code goes here. 
        if (e == INVALID_STATE_ERR) { 
            // Version number mismatch. 
            alert("Invalid database version."); 
        } else { 
            alert("Unknown error "+e+"."); 
        } 
        return; 
    } 
}

function testUpload()
{
var result;
var currentTime=new Date();
var d=zeroPad(currentTime.getDate());
var mo=zeroPad(currentTime.getMonth()+1);
var y=currentTime.getFullYear();
var h=zeroPad(currentTime.getHours());
var m=zeroPad(currentTime.getMinutes());
var s=zeroPad(currentTime.getSeconds());

var ctimestamp = y+"-"+mo+"-"+d+"-"+h+"-"+m+"-"+s;
var theStamp = ctimestamp;
localStorage.setItem("fileTime",theStamp);
	
	result=connectionCheck();
	alert("Network availability: "+result);
	
	
	if(result==true)
	{
		
		connectionAvailable=false;
		serverPing();
		alert("Internet access : "+connectionAvailable);
		//setTimeout(function(){removeCustomAlert()},2000);
		Popup.showModal('modal',null,null,{'screenColor':'#99ff99','screenOpacity':.6});
		uploadSync();
	}
	return connectionAvailable; //<---- this line
}

function serverPing()
{
	var xhr = new XMLHttpRequest();
	
	xhr.open("HEAD", pingURL, false);//false - non asynchronous request, dont make it true !!
	
	xhr.onreadystatechange = function() 
	{
		//alert(xhr.readyState+" "+xhr.status);
		
		switch(xhr.readyState)
		{
			case 2:
				if(xhr.status==200)
				{
					connectionAvailable=true;
					xhr.onreadystatechange=null;
					
					
				}
				if(xhr.status==0)
				{
					connectionAvailable=false;
					xhr.onreadystatechange=null;
				}
				break;
			case 4:
				if(xhr.status==200)
				{
					connectionAvailable=true;
					xhr.onreadystatechange=null;
				}
				if(xhr.status==0)
				{
					connectionAvailable=false;
					xhr.onreadystatechange=null;
				}
				break;
		}
    }
	
	try
	{
		xhr.send();
	}
	catch(e)
	{
		connectionAvailable=false;
		xhr.onreadystatechange=null;
	}
}

function connectionCheck()
{
	var networkState = navigator.connection.type;

    /*var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.NONE]     = 'No network connection';
	*/

    if(networkState!=Connection.UNKNOWN && networkState!=Connection.NONE)
    	return true;
    else
    	return false;
}

function uploadSync()
{
	getLastSyncTimestamp();
	//setProgress('element1','0');
	//Popup.showModal('modalProgress',null,null,{'screenColor':'#99ff99','screenOpacity':.6});
}

function getLastSyncTimestamp()
{
	mydb.transaction(
		function(tx)
		{
		    tx.executeSql
		    (
		    	'SELECT timestamp FROM last_sync order by timestamp desc limit 1', 
		    	[],
		    	getLastSyncTimestampSuccess,
		    	getLastSyncTimestampFailed
			);
		}
	);
}

function getLastSyncTimestampSuccess(tx, result)
{
	if(result.rows.length==0){
		lastSyncTimestamp="0000-00-00 00:00:00";
		
	}
	else
	{
		lastSyncTimestamp=result.rows.item(0).timestamp;
	}
	//alert(lastSyncTimestamp);
	// getUploadRecords();
	doImageResize();
}

window.imageResize = function(resizeSuccessCB,params)
	{
    	cordova.exec(resizeSuccessCB, failCB, "ImageResize", null, params);
	};
	
	function doImageResize()
	{
		mydb.transaction(getList);
	}

function getList(tx) {
		var logQuery="";
		if(lastSyncTimestamp=="0000-00-00 00:00:00"){
		logQuery= 'SELECT * FROM sku_check_photo order by photo_date';
		}
		else{
		logQuery= 'SELECT * FROM sku_check_photo where photo_date >"'+lastSyncTimestamp+'" order by photo_date';
		}
		tx.executeSql(logQuery,[],getLogListSuccess,getFileListQueryError);
	}
	
	function getLogListSuccess(tx,result){
	dataset = result.rows;
	 if(dataset.length>0)//atleast one record was found
    {

		 for (var p = 0, item  = null; p < dataset.length; p++) {

		  item= dataset.item(p);
			sourcePaths.push(item['photo_name'].substring(7,100));
		}
		//           resizeImage(sourcePaths,640,480);
        mydb.transaction(getCensusList);
	}else{
		 mydb.transaction(getCensusList);
		alert("No sku check photo for uploading.");
	}
}

function getCensusList(tx){
	var censusPhotoQuery="";
		if(lastSyncTimestamp=="0000-00-00 00:00:00"){
		censusPhotoQuery= 'SELECT * FROM outlet_census_photo order by photo_date';
		}
		else{
		censusPhotoQuery= 'SELECT * FROM outlet_census_photo where photo_date >"'+lastSyncTimestamp+'" order by photo_date';
		}
		tx.executeSql(censusPhotoQuery,[],getCensusListSuccess,getFileListQueryError);
}

	function getCensusListSuccess(tx,result){
	dataset = result.rows;
	 if(dataset.length>0)//atleast one record was found
    {

		 for (var p = 0, item  = null; p < dataset.length; p++) {

		  item= dataset.item(p);
			sourcePaths.push(item['photo_name'].substring(7,100));
		}
		//           resizeImage(sourcePaths,640,480);
        resizeImage(sourcePaths,640,480);
	}else{
		getUploadRecords();
		alert("No census photo for uploading.");
	}
}
	
	//wrapper function, use this when you want
	function resizeImage(sourcePathArray,targetWidth,targetHeight)
	{
		var params=new Array();
		
		params[0]=sourcePathArray;
		params[1]=targetWidth;params[2]=targetHeight;
	
		window.imageResize(getUploadRecords,params);
	}	
	
	function failCB(err)
	{
		alert("error:"+err.message);
		Popup.hide('modal');
	}
	
function resizeSuccessCB(result)
{
	var failedPaths=eval("("+result+")");
		
	//@note: all images have been resized successfully
	if(failedPaths.length==0){
		alert("All images resized successfully");
	}
	else
	{
		alert("All images could not be resized successfully");
		//@note: we list out all the images that could not be resized
		//further action needs to be taken from here
		for(var i=0;i<failedPaths.length;i++)
		alert(failedPaths[i]);
	}
		
}	

function getFileListQueryError(err)
{
    console.log("getFileListQueryError");
}

/*
    function uploadFiles()
    {
    	var url;
    	
		url="https://intensecontrol.com/dksh/main/tablet_upload_act.jsp"; //put in the ip address of the server to ping here
    	
    	setProgress('element1','0');
		Popup.showModal('modalProgress',null,null,{'screenColor':'#99ff99','screenOpacity':.6});
       
        setURL(url);
        mydb.transaction(getFileList,getFileListError,getFileListSuccess);
    }


function getFileList(tx)
    {
    	var sqlQuery="";
		console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> inside getFileList");
		if(lastSyncTimestamp=="0000-00-00 00:00:00")
		{
			sqlQuery= 'SELECT * FROM sku_check_photo order by photo_date';
			//console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> inside if: "+sqlQuery);
		}
		else
		{
			sqlQuery= 'SELECT * FROM sku_check_photo where photo_date >"'+lastSyncTimestamp+'" order by photo_date';
			//console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> inside else: "+sqlQuery);
		} 
		
        tx.executeSql(sqlQuery, [], getFileListQuerySuccess, getFileListQueryError);
    }
	
	

    
    function getFileListSuccess()
	{
		console.log("getFileListSuccess");
	}
	
	function getFileListError(err)
	{
	    console.log("getFileListError");
	}
 
  function getFileListQuerySuccess(tx, result2)
    {
    	dataset2 = result2.rows;
    	//console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> inside for loop found rows : "+result2.rows.length);
   		
        
        for (var p = 0, item = null; p < dataset2.length; p++)
        {
    	    item = dataset2.item(p);
		    //fileList.push(item['photo_name'].substr(item['photo_name'].indexOf("t")+1));
			fileList.push(item['photo_name']);
		    //console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> pushing item : "+item['photo_name']);
		}
		setFileList(fileList);
		//console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> initiating batch file upload");
		startBatchFileUpload(uploadCompleted);
    }
	
    function uploadCompleted(failedPaths)
    {
    	var length=failedPaths;
    	
    	Popup.hide('modalProgress');
    	
    	if(length==0){
        	alert("All files uploaded");
        	console.log("All files uploaded");
			getUploadRecords();
		}
        else
        {
        	alert("Some files could not be uploaded");
        	console.log("Some files could not be uploaded");
        	for(var i=0;i<failedPaths.length;i++)
        		console.log(failedPaths[i]);
        }
    }
*/
function getLastSyncTimestampFailed(err)
{
	alert(err);
	Popup.hide('modal');
}

function getUploadRecords()
{
	mydb.transaction(
		function(tx)
		{
			var select="";
			
			if(lastSyncTimestamp=="0000-00-00 00:00:00"){
				select="SELECT * FROM sql_sync order by timestamp";
			}
			else{
				select="SELECT * FROM sql_sync where timestamp>'"+lastSyncTimestamp+"' order by timestamp ";
			}
			
		    tx.executeSql
		    (
		    	select, 
		    	[],
		    	getUploadRecordsSuccess,
		    	getUploadRecordsFailed
			);
		}
	);
}

function getUploadRecordsFailed(err)
{
	alert(err);
	Popup.hide('modal');
}

function getUploadRecordsSuccess(tx,result)
{
	var numRows = result.rows.length;
	
	var id,sql_statement,timestamp;
	var insert;

	for (i=0;i<numRows;i++)
	{
		id=result.rows.item(i).id;
		sql_statement=result.rows.item(i).sql_statement;
		timestamp=result.rows.item(i).timestamp;

		if(i<numRows)//it's important that the records arrive in latest timestamp first order
			lastRecordTimestamp=timestamp;
		
		fileData=fileData+sql_statement+"\n";//fileData is global
		//alert(statement);
	}
	
	//@note: put a check here to see if atleast one row has been generated
	if(numRows>0){
		writeDataToFile();
	}
	else{
		Popup.hide('modal');
		alert("No data available for upload");
	}
}

function writeDataToFile()
{
	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem)
{
	//@note: filenaming convention needs to be changed as per jj's requirement
	fileSystem.root.getFile("iControl/"+device.uuid+"-"+localStorage.getItem("fileTime")+".txt", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry)
{
    fileEntry.createWriter(gotFileWriter, fail);
}

function fail(error)
{
	console.log(error.code);
	Popup.hide('modal');
}

function gotFileWriter(writer)
{
	writer.onwriteend = writeSuccessCB;
	writer.write(fileData);

}

function writeSuccessCB(evt)
{	
	setTimeout(doGenerateZip(),500);
	console.log("Success!!");
}

function updateSyncSuccess()
{
	mydb.transaction(
		function(tx)
		{
			var insert="INSERT into last_sync(timestamp) values('"+lastRecordTimestamp+"')";
			
		    tx.executeSql
		    (
		    	insert, 
		    	[],
		    	updateSyncTimestampSuccess,
		    	updateSyncTimestampFailed
			);
		}
	);
}

function updateSyncTimestampFailed(err)
{
	alert(err);
	Popup.hide('modal');
}

function updateSyncTimestampSuccess(tx,result)
{
	Popup.hide('modal');
	alert("Export successful!");
	alert("Sync update success");
	processDeleteFile2();
	console.log("successCB");
}

function zeroPad(input)
	{
		return (input<10?("0"+input):input); 
	}